/**
* Copyright (c) 2016-2100 yunclouds
*/
package com.yunqian.redot.service;

import com.yunqian.redot.constant.OrderStatus;
import com.yunqian.redot.domain.CoursesOrder;
import com.yunqian.redot.repository.CoursesOrderRepository;
import com.yunqian.service.BaseService;
import com.yunqian.util.RandomUtil;
import com.yunqian.util.swiftpass.SwiftpassUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 客户课程报名记录
 *
 * @author zsy
 * 2018-09-29 15:54:11
 */
@Service
@Log4j2
public class CoursesOrderService extends BaseService<CoursesOrder, Long> {

    @Autowired
    private CoursesOrderRepository coursesOrderRepository;
    @Autowired
    private SwiftpassPayService swiftpassPayService;

    public Map<String,String> saveOrder(CoursesOrder coursesOrder, String openId, String ip) {
        // 保存订单
        String orderNo = "NO" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + RandomUtil.fourDigit();
        coursesOrder.setOrderNo(orderNo);
        // 如果订单金额为0 直接置为支付成功状态 并且前端不需要调用支付
        if(BigDecimal.ZERO.compareTo(coursesOrder.getPrice()) == 0){
            coursesOrder.setStatus(OrderStatus.SUCCESS.getCode());
        }
        CoursesOrder order = super.save(coursesOrder);
        // 订单支付 -预下单
        Map<String,String> params = SwiftpassUtil.prepayment(order.getOrderNo(), "课程订单", openId, "course_order", String.valueOf(order.getPrice()), ip);
        params.put("orderId", order.getId().toString());
        // 保存预下单信息
        swiftpassPayService.save(order.getOrderNo(), params);
        return params;
    }

    public void updateOrderStatus(){
        coursesOrderRepository.updateOrderStatus();
    }

    public CoursesOrder findByOrderNo(String orderNo){
        return coursesOrderRepository.findByOrderNo(orderNo);
    }


    public List<CoursesOrder> getByOrderNoAndPhoneAndRangeTime(String orderNo, String phone, String beginTime, String endTime){
        return coursesOrderRepository.findByOrderNoAndPhoneAndRangeTime(orderNo,phone,beginTime,endTime);
    }

    public boolean existsByCustomerIdAndCourseId(Long customerId, Long courseId){
        return coursesOrderRepository.existsByCustomerIdAndCourseId(customerId, courseId);
    }

}
